'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');

class ClassService extends Service {
  /**
   * 根据分页和搜索条件获取班级
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条

   */
  async getPage(where, page, pageSize) {
    const { Class, School } = this.ctx.model;

    try {
        const res = Class.findAndCountAll({
            where: {
                ...where
            },
            order:[
                // id 降序
                ['created_at','DESC']
            ],
            include: [
              {model: School, as: 'school'},
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
        return res
    } catch (e) {
    }
  }

  /**
   * 注册用户数据
   * @param {Object} data
   */
  async createItem(data) {
    const { Class } = this.ctx.model;
    const userExists = await Class.findOne({
      attributes: ['id'],
      where: {
        [Op.or]: {
          class_name: data.class_name,
        },
      },
    });
    if (userExists) throw new Error('该课程已经存在');
    const newUser = await Class.create(data);
    return newUser.dataValues;
  }

  /**
   * 根据id删除对应的用户
   * @param {Number} uid
   */
  async deleteItemById(id) {
    return await this.ctx.model.Class.destroy({ where: { id } });
  }

  /**
   * 根据ID修改用户信息
   * @param {Number} id 用户ID
   * @param {Object} data 要修改的用户信息
   */
  async updateItemById(id, data) {
    const { Class } = this.ctx.model;
    const { class_name } = data;
    const andWhere = { id: { [Op.ne]: id } };
    let neenCheck = false;
   if (class_name) {
      neenCheck = true;
      andWhere.class_name = class_name;
    }

    if (neenCheck) {
      const userExists = await Class.findOne({
        attributes: ['id'],
        where: { [Op.and]: andWhere },
      });
      if (userExists) throw new Error('该账号已经存在');
    }

    return await Class.update(data, { where: { id } });
  }
  /**
   * 更新用户密码
   * @param {Number} id 用户ID
   * @param {Object} data 新密码和旧密码
   */
  async updatePassword(id, data) {
    const { Class } = this.ctx.model;
    const user = await Class.findByPk(id);
    if (!user) {
      throw new Error('该账号不存在');
    }

    // 旧密码是否有误, 正确就直接修改
    const isValid = bcrypt.compareSync(data.old_password, user.password);
    if (!isValid) {
      throw new Error('账号或密码有误');
    }
    user.password = data.new_password;
    return await user.save();
  }

  // 所有列表
  async allList(where) {
    const { Class } = this.ctx.model;
    return Class.findAll({
      where
    });
  }
}

module.exports = ClassService;
